package com.example.zhihu.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author Jack
 * <p>date  2021/3/3 14:59<p>
 */
@Component
public class HttpUtils {
    static PoolingHttpClientConnectionManager connectionManager;
    public HttpUtils() {
        connectionManager = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        connectionManager.setMaxTotal(100);
        // 设置每个主机的最大连接数
        connectionManager.setDefaultMaxPerRoute(10);

    }
    /**
     * 根据请求地址下载页面数据
     * @param url
     * @return String
     */
    public static String doGetHtml(String url) {
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
        // 设置HttpGet请求对象
        HttpGet httpGet = new HttpGet(url);
        // 设置请求信息
        httpGet.setConfig(getConfig());
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");
        // 使用HttpClient发起请求，获取响应
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            // 解析响应，返回结果
            if(response.getStatusLine().getStatusCode() == 200) {
                if(response.getEntity() != null) {
                    return EntityUtils.toString(response.getEntity(), "utf8");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(response != null) {
                    response.close();
                }
                response = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 下载图片，返回图片名称
     * @param url
     * @return String
     */
    public static String doGetImage(String url) {
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
        // 设置HttpGet请求对象
        HttpGet httpGet = new HttpGet(url);
        // 设置请求信息
        httpGet.addHeader("Accept", "text/html");
        httpGet.addHeader("Accept-Charset", "utf-8");
        httpGet.addHeader("Accept-Encoding", "gzip");
        httpGet.addHeader("Accept-Language", "zh-CN,zh");
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
        httpGet.setConfig(getConfig());

        // 使用HttpClient发起请求，获取响应
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            // 解析响应，返回结果
            if(response.getStatusLine().getStatusCode() == 200) {
                if(response.getEntity() != null) {
                    // 下载图片，并写入到本地
                    String extName = url.substring(url.lastIndexOf("."));
                    String picName = UUID.randomUUID().toString() + extName;
                    OutputStream outputStream = new FileOutputStream(new File("D:\\images\\" + picName));
                    response.getEntity().writeTo(outputStream);
                    return picName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(response != null) {
                    response.close();
                }
                response = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 设置请求信息
     * @return RequestConfig
     */
    private static RequestConfig getConfig() {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(5000).setSocketTimeout(10000).build();
        return requestConfig;
    }

}
